﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using University.Workshop.Model;
using System.IO;
using University.Workshop.Business;
using University.Workshop.DataAccess;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Web.Security;
using System.Web.UI.HtmlControls;
using System.Net;
using System.Text.RegularExpressions;

namespace University.Workshop.WebApp
{
    public partial class ProductSelected : System.Web.UI.Page
    {

        public Product selectedProductItem = null;
        public Collection<Product> products = null;
        public Collection<WatchListItem> items = null;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!User.Identity.IsAuthenticated)
                FormsAuthentication.RedirectToLoginPage();
            else
            {
                fbLabel.Text = "<div id=\"fb-root\"></div>" +
                 "<script type=\"text/javascript\">" +
                "(function (d, s, id) {" +
                "var js, fjs = d.getElementsByTagName(s)[0];" +
                "if (d.getElementById(id)) return;" +
                "js = d.createElement(s); js.id = id;" +
                "js.src = \"//connect.facebook.net/en_US/all.js#xfbml=1&appId=432440856766538\";" +
                "fjs.parentNode.insertBefore(js, fjs);" +
                "} (document, 'script', 'facebook-jssdk'));</script>" +
                "<fb:like href=\"" + GetFBUrl() + "\" send=\"false\" width=\"450\" show_faces=\"false\" action=\"recommend\">" +
                "</fb:like>";
                User user = new User();
                user = UserDataAccess.GetUserByEmail(User.Identity.Name);
                products = new Collection<Product>();
                name.Text = Request["ProductName"];
                productId.Text = Request["ProductID"];
                Category.Text = Request["ProductCategory"];
                GridView1.DataSource = ViewProductManager.LoadCompleteInformation(productId.Text);
                GridView1.DataBind();
                Product prod = ProductDataAccess.GetProductById(Convert.ToInt64(productId.Text));
                this.selectedProductItem = prod;
                LoadInformation(prod);
                loadViewed(prod);
                loadBought(prod);
                loadFrequent(prod);
                if (!IsPostBack)
                {
                    PageViewed(prod, user);
                }

                //FOR WISHLIST
                ForWishList.DataSource = UserWishListDataAccess.GetProductBYUserId(user.Id);
                ForWishList.DataBind();
            }
        }

        public void loadFrequent(Product prod)
        {
            Collection<long> products = OrderDataAccess.GetFrequentlyBoughtTogether(prod.ProductId);
            if (products != null && products.Count != 0)
            {
                together.Visible = true;
                lvHeader3.Text = "Frequently bought together with this product";
                lvHeader3.Font.Bold = true;
                lvHeader3.Font.Size = FontUnit.XLarge;
                lvHeader3.ForeColor = System.Drawing.Color.FromName("#4B6C9E");
                TableRow tr = new TableRow();
                int max = (products.Count > 4) ? 4 : products.Count;
                for (int i = 0; i < max; i++)
                {
                    TableCell td = new TableCell();
                    ProductInformation p = (ProductInformation)Page.LoadControl("~/ProductInformation.ascx");
                    Product product = ProductDataAccess.GetProductById(products[i]);
                    if (Directory.Exists(Server.MapPath("~/Thumbnails/") + product.ProductId + "/"))
                    {
                        DirectoryInfo dir = new DirectoryInfo(Server.MapPath("~/Thumbnails/") + product.ProductId + "/");
                        FileInfo[] currentImages = dir.GetFiles();
                        string thumbUrl = "~/Thumbnails/" + product.ProductId + "/";
                        foreach (FileInfo fi in currentImages)
                        {
                            if (String.IsNullOrEmpty(image1.ImageUrl))
                            {
                                p.img.ImageUrl = thumbUrl + fi.Name;

                            }
                        }
                    }
                    else
                    {
                        p.img.ImageUrl = "~/Thumbnails/NoImage/noimage.jpg";
                    }
                    p.hLink.Text = product.Name;
                    p.link += product.ProductId + "&ProductName=" + product.Name + "&ProductPrice=" + product.Price + "&ProductCategory=" + product.Category;
                    p.lPrice.Text = "Precio: " + product.Price;
                    if (product.Currency == " Dollars")
                        p.lPrice.Text += "$us.";
                    else
                        p.lPrice.Text += " Bs.";
                    td.Controls.Add(p);
                    td.VerticalAlign = VerticalAlign.Top;
                    tr.Cells.Add(td);
                }
                tblDynamic3.Rows.Add(tr);
            }
            else
            {
                together.Visible = false;
            }
        }

        public void loadBought(Product prod)
        {
            Collection<long> products = OrderDataAccess.GetMostBought(prod.ProductId);
            if (products != null && products.Count != 0)
            {
                bought.Visible = true;
                lvHeader2.Text = "Users that bought this product also bought";
                lvHeader2.Font.Bold = true;
                lvHeader2.Font.Size = FontUnit.XLarge;
                lvHeader2.ForeColor = System.Drawing.Color.FromName("#4B6C9E");
                TableRow tr = new TableRow();
                int max = (products.Count > 4) ? 4 : products.Count;
                for (int i = 0; i < max; i++)
                {
                    TableCell td = new TableCell();
                    ProductInformation p = (ProductInformation)Page.LoadControl("~/ProductInformation.ascx");
                    Product product = ProductDataAccess.GetProductById(products[i]);
                    if (Directory.Exists(Server.MapPath("~/Thumbnails/") + product.ProductId + "/"))
                    {
                        DirectoryInfo dir = new DirectoryInfo(Server.MapPath("~/Thumbnails/") + product.ProductId + "/");
                        FileInfo[] currentImages = dir.GetFiles();
                        string thumbUrl = "~/Thumbnails/" + product.ProductId + "/";
                        foreach (FileInfo fi in currentImages)
                        {
                            if (String.IsNullOrEmpty(image1.ImageUrl))
                            {
                                p.img.ImageUrl = thumbUrl + fi.Name;

                            }
                        }
                    }
                    else
                    {
                        p.img.ImageUrl = "~/Thumbnails/NoImage/noimage.jpg";
                    }
                    p.hLink.Text = product.Name;
                    p.link += product.ProductId + "&ProductName=" + product.Name + "&ProductPrice=" + product.Price + "&ProductCategory=" + product.Category;
                    p.lPrice.Text = "Precio: " + product.Price;
                    if (product.Currency == " Dollars")
                        p.lPrice.Text += "$us.";
                    else
                        p.lPrice.Text += " Bs.";
                    td.Controls.Add(p);
                    td.VerticalAlign = VerticalAlign.Top;
                    tr.Cells.Add(td);
                }
                tblDynamic2.Rows.Add(tr);
            }
            else
            {
                bought.Visible = false;
            }

        }

        public void loadViewed(Product prod)
        {
            Collection<long> products = OrderDataAccess.GetMostBoughtByViewed(prod.ProductId);
            if (products != null && products.Count != 0)
            {
                viewed.Visible = true;
                lvHeader.Text = "Users that viewed this product also bought";
                lvHeader.Font.Bold = true;
                lvHeader.Font.Size = FontUnit.XLarge;
                lvHeader.ForeColor = System.Drawing.Color.FromName("#4B6C9E");
                TableRow tr = new TableRow();
                int max = (products.Count > 4) ? 4 : products.Count;
                for (int i = 0; i < max; i++)
                {
                    TableCell td = new TableCell();
                    ProductInformation p = (ProductInformation)Page.LoadControl("~/ProductInformation.ascx");
                    Product product = ProductDataAccess.GetProductById(products[i]);
                    if (Directory.Exists(Server.MapPath("~/Thumbnails/") + product.ProductId + "/"))
                    {
                        DirectoryInfo dir = new DirectoryInfo(Server.MapPath("~/Thumbnails/") + product.ProductId + "/");
                        FileInfo[] currentImages = dir.GetFiles();
                        string thumbUrl = "~/Thumbnails/" + product.ProductId + "/";
                        foreach (FileInfo fi in currentImages)
                        {
                            if (String.IsNullOrEmpty(image1.ImageUrl))
                            {
                                p.img.ImageUrl = thumbUrl + fi.Name;

                            }
                        }
                    }
                    else
                    {
                        p.img.ImageUrl = "~/Thumbnails/NoImage/noimage.jpg";
                    }
                    p.hLink.Text = product.Name;
                    p.link += product.ProductId + "&ProductName=" + product.Name + "&ProductPrice=" + product.Price + "&ProductCategory=" + product.Category;
                    p.lPrice.Text = "Precio: " + product.Price;
                    if (product.Currency == " Dollars")
                        p.lPrice.Text += "$us.";
                    else
                        p.lPrice.Text += " Bs.";
                    td.Controls.Add(p);
                    td.VerticalAlign = VerticalAlign.Top;
                    tr.Cells.Add(td);
                }
                tblDynamic.Rows.Add(tr);
            }
            else
            {
                viewed.Visible = false;
            }
        }

        public void PageViewed(Product prod, User user)
        {
            CultureInfo.GetCultureInfo("en-US");
            string userId = user.Id.ToString(CultureInfo.GetCultureInfo("en-US"));
            string prodId = prod.ProductId.ToString(CultureInfo.GetCultureInfo("en-US"));
            ViewProductManager.PageViewed(userId, prodId);
        }

        public void LoadInformation(Product prod)
        {

            if (Directory.Exists(Server.MapPath("~/Thumbnails/") + prod.ProductId + "/"))
            {
                DirectoryInfo dir = new DirectoryInfo(Server.MapPath("~/Thumbnails/") + prod.ProductId + "/");
                FileInfo[] currentImages = dir.GetFiles();
                string thumbUrl = "~/Thumbnails/" + prod.ProductId + "/";
                foreach (FileInfo fi in currentImages)
                {
                    if (String.IsNullOrEmpty(image1.ImageUrl))
                    {
                        image1.ImageUrl = thumbUrl + fi.Name;

                    }
                }
            }
            else
            {
                image1.ImageUrl = "~/Thumbnails/NoImage/noimage.jpg";
            }
        }

        public string GetProductImage()
        {
            string imageURL;
            string ProductId = Request["ProductID"];
            if (Directory.Exists(Server.MapPath("~/Images/") + ProductId + "/"))
            {
                DirectoryInfo dir = new DirectoryInfo(Server.MapPath("~/Images/") + ProductId + "/");
                FileInfo[] currentImages = dir.GetFiles();
                string imgUrl = "/Images/" + ProductId + "/";
                imageURL = "http://" + Request.Url.Host + ":" + Request.Url.Port + imgUrl + currentImages[0].Name;
            }
            else
            {
                imageURL = "http://" + Request.Url.Host + ":" + Request.Url.Port + "/Thumbnails/NoImage/noimage.jpg";
            }
            return imageURL;
        }

        public string GetFBUrl()
        {
            return Request.Url.ToString();
        }

        public string GetName()
        {
            return Request["ProductName"];
        }

        public string GetDescription()
        {
            return ProductDataAccess.GetProductDescription(Request["ProductID"]);
        }

        protected void LinkButton1_Click(object sender, EventArgs e)
        {
            Response.Redirect("ViewProduct.aspx");
        }


        //Create a product recommendation with it's name 
       /* public void BuildProdRecommManager()
        {
            ProductRecommendationManager prm = new ProductRecommendationManager();
            prm.Prod = this.selectedProductItem;
            prm.MatchWords = ViewProductManager.SplitString(this.selectedProductItem.Name);
            this.productRecomm = prm;
        }

        public void productMatches()
        {
            
                foreach (GridViewRow row in GridView2.Rows)
                {
                    Product prodAux = new Product();
                    prodAux.ProductId = Convert.ToInt64(row.Cells[0].Text);
                    prodAux.Name = row.Cells[1].Text;
                    if (this.selectedProductItem.ProductId != prodAux.ProductId)
                    {
                        ProductRecommendationManager prmaux = new ProductRecommendationManager();
                        prmaux.Prod = prodAux;
                        prmaux.MatchWords = ViewProductManager.SplitString(prodAux.Name);
                        bool res = ProductRecommendationManager.AlmostSameNames(selectedProductItem.Name, prodAux.Name);
                        if (res)
                            ProductDataAccess.InsertProductRecommendation(selectedProductItem,prodAux);
                    }
                }
            
               
        }*/

        protected void LinkButton2_Click(object sender, EventArgs e)
        {
            Response.Redirect("ProductRecommendation.aspx?ProductID=" + productId.Text + "&ProductName=" + name.Text + "&ProductCategory=" + Category.Text);
        }
         

        protected void buyNow_Click(object sender, EventArgs e)
        {
            try
            {
                products = new Collection<Product>();
                Product prod = ProductDataAccess.GetProductById(long.Parse(productId.Text, CultureInfo.CurrentCulture));
                short quantity = short.Parse(xQuantity.Text, CultureInfo.CurrentCulture);
                if (quantity >= 1 && quantity <= prod.Quantity)
                {
                    prod.Quantity = quantity;
                    products.Add(prod);
                    Session["list"] = products;
                    //For GiftCard:
                    bool creditEnough = true;
                    float productPrice = prod.Price;
                    for (int i = 0; i < quantity ; i = i + 1)
                    {

                        if (!CanIBuyProduct(UserDataAccess.GetUserByEmail(User.Identity.Name).Id, productPrice, prod.Currency))
                        {
                            creditEnough = false;
                            break;
                        }
                        productPrice = float.Parse(int.Parse(productPrice.ToString()) + int.Parse(productPrice.ToString()).ToString());

                    }
                    if(creditEnough)
                            Response.Redirect("BuyWithGiftCard.aspx?ProductId="+prod.ProductId+ "&QuantitySpended="+prod.Price+"&itemsQuantity="+quantity);
                    else
                            Response.Redirect("Checkout.aspx");

                }
                else
                    throw new ValidationException("Invalid quantity");
            }
            catch (Exception ex)
            {
                lError.Visible = true;
                lError.Text = ex.Message;
            }
        }

        protected void addToCart_Click(object sender, EventArgs e)
        {
            try
            {
                bool isInShoppingCart = false;
                Product prod = ProductDataAccess.GetProductById(long.Parse(productId.Text, CultureInfo.CurrentCulture));
                products = Session["carrito"] as Collection<Product>;
                if (products != null)
                {
                    foreach (var item in products)
                    {
                        if (item.ProductId == prod.ProductId)
                        {
                            Response.Write("<script>alert('That Product Is already in your Cart!'); </script>");
                            isInShoppingCart = true;
                            break;
                        }
                    }
                }
                if (products == null)
                {
                    products = new Collection<Product>();
                    Session["carrito"] = products;
                }
                
                short quantity = short.Parse(xQuantity.Text, CultureInfo.CurrentCulture);
                if (quantity >= 1 && quantity <= prod.Quantity)
                {
                    prod.Quantity = quantity;
                    Session["products"] = prod;
                    if (!isInShoppingCart)
                    {
                        Response.Redirect("ShoppingCart.aspx");
                    }
                    
                }
                else
                    throw new ValidationException("Invalid quantity");
            }
            catch (Exception ex)
            {
                lError.Visible = true;
                lError.Text = ex.Message;
            }
        }

        protected void Rate_Click(object sender, EventArgs e)
        {
            Response.Redirect("RateProduct.aspx?ProductID=" + productId.Text + "&ProductName=" + name.Text + "&ProductCategory=" + Category.Text);

        }

        protected void wishlistButton_Click(object sender, EventArgs e)
        {
            if (!User.Identity.IsAuthenticated)
                FormsAuthentication.RedirectToLoginPage();
            else
            {
                User user = UserDataAccess.GetUserByEmail(User.Identity.Name);
                Product product = ProductDataAccess.GetProductById(System.Convert.ToInt64(productId.Text));
                string status;
                if (product.Quantity > 0)
                    status = "Available";
                else
                    status = "Unavailable";
                bool isInWishList = false;

                //para saber si los productos en myWishList contiene al producto que se ha seleccionado
                foreach (GridViewRow row in ForWishList.Rows)
                {
                    if (System.Convert.ToInt64(row.Cells[0].Text) == product.ProductId)
                    {
                        Response.Write("<script>alert('That Product Is already in your WISHLIST!');  window.location.href = 'ProductSelected.aspx?ProductID=" + product.ProductId + "&ProductName=" + product.Name + "&ProductPrice=" + product.Price + "&ProductCategory=" + product.Category+ "';</script>");
                        isInWishList = true;
                        break;
                    }
                }


                if (!isInWishList)
                {
                    UserWishListManager.RegisterWishList(user.Id, System.Convert.ToInt64(productId.Text), status);
                    Response.Write("<script>alert('Added to your WISHLIST!'); window.location.href = 'ViewUserWishList.aspx'; </script>");
                }



            }

        }


        protected void watchlistButton_Click(object sender, EventArgs e)
        {
            try
            {
                Product prod = ProductDataAccess.GetProductById(long.Parse(productId.Text, CultureInfo.CurrentCulture));
                items = Session["watched"] as Collection<WatchListItem>;
                bool isInWatchList = false;
                if (items != null)
                {
                    foreach (var item in items)
                    {
                        if (item.RelatedProduct.ProductId == prod.ProductId)
                        {
                            Response.Write("<script>alert('That Product Is already in your WatchList!'); </script>");
                            isInWatchList = true;
                            break;
                        }
                    }
                }
                if (items == null)
                {
                    items = new Collection<WatchListItem>();
                    Session["watched"] = items;
                }
                User user = UserDataAccess.GetUserByEmail(User.Identity.Name);
                
                Session["prod"] = prod;
                if (!isInWatchList)
                {
                    Response.Redirect("WatchList.aspx");
                }
            }
            catch (Exception ex)
            {
                lError.Visible = true;
                lError.Text = ex.Message;
            }
        }

        protected void MakeOffer_Click(object sender, EventArgs e)
        {
            Product prod = ProductDataAccess.GetProductById(long.Parse(productId.Text, CultureInfo.CurrentCulture));
            User user=UserDataAccess.GetUserByEmail(User.Identity.Name);
            bool isOffered = false;
            bool isMine=false;
            Collection<Offer> offer = new Collection<Offer>();
            offer = OfferManager.GetOffersByBuyerId(user.Id);
            if (offer != null)
            {
                foreach (var item in offer)
                {
                    if (item.RelatedProduct.ProductId == prod.ProductId)
                    {
                        Response.Write("<script>alert('You have already make a offer for this product!'); </script>");
                        isOffered = true;
                        break;
                    }
                }       
            }
            if (user.Id == prod.SellerId)
            {
                Response.Write("<script>alert('You own this product, you can't make an offer!'); </script>");
                isMine = true;

                lError.Visible = true;
                lError.Text = "You own this product, you can't make an offer!";
            }
            Session["prod"] = prod;
            if (!isOffered && !isMine)
                Response.Redirect("MakeAOffer.aspx");

           
        }

        //For Gift Card
        protected GiftCard UserHasGiftCard(long userId)
        {
            return GiftCardManager.GetGiftCardByRecipientId(userId); 
        }
        protected float GetCredit(GiftCard giftcard)
        {
            return giftcard.Quantity;
        }
        protected bool IsMyCreditEnough(float productPrice,float giftCardQuantity,string productCurrency,string giftcardCurrency)
        {
            int productPriceInt = int.Parse(productPrice.ToString());
            int giftCardQuantityInt = int.Parse(giftCardQuantity.ToString());
            if (productCurrency == giftcardCurrency)
            {
                if (giftCardQuantity >= productPrice)
                    return true;
                else
                    return false;
            }
            else
            {
                if (productCurrency == "Bolivianos")
                {
                    giftCardQuantityInt = giftCardQuantityInt / 7;
                    if (giftCardQuantityInt >= productPriceInt)
                        return true;
                    else
                        return false;
                }
                else
                {
                    giftCardQuantityInt = giftCardQuantityInt * 7;
                    if (giftCardQuantityInt >= productPriceInt)
                        return true;
                    else
                        return false;
                }
            }
               
        }
        protected bool CanIBuyProduct(long userId,float productPrice,string productCurrency)
        {
            
            GiftCard giftcard = UserHasGiftCard(userId);
            if (giftcard != null)
            {
                bool isEnough = IsMyCreditEnough(productPrice, giftcard.Quantity, productCurrency, giftcard.Currency);
                if (isEnough)
                    return true;
            }
            return false;
        }

        protected void ViewProductLB_Click(object sender, EventArgs e)
        {
            Response.Redirect("ProductCompleteInformation.aspx?ProductID=" + productId.Text + "&ProductName=" + name.Text + "&ProductCategory="+ Category.Text);
        }
       

    }
}
